/**
 * Created by shao-yikun on 2017/5/4.
 */

var groupOrgIds = 0;
var groupOrgCount = 0;
var fullFlag = false;
var height = 0;
var width = 0;

$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_noticeadd/getNoticesended4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTables').DataTable().search(this.value);
            }
        },
        columns: [{
            data: "noticeId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: "userNoticeId",
            targets: 0
        }, {
            data: "noticeTitle"
        }, {
            data: "noticeSendTime",
            render: function (data, type, row, meta) {
                return data.substring(0, 10);
            }
        }, {
            data: "userNoticeId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限
                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deleteSelectNotice(" + JSON.stringify(row) + ")' title='删除'><i class='fa fa-minus-square'></i></button>";
                var buttonSelect = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showNotice(" + JSON.stringify(row) + ")' title='详情'><i class='glyphicon glyphicon-eye-open'></i></button>";
                var buttonOperation = "";
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonSelect + " ";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;
                buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>";
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button></li>";
            // 下拉工具栏不处理更新事件，但今后可能需要审核等功能，替换该位置即可
            //var buttonUpdate = "<li><button href='#' class='btn btn-warning btn-sm btn-flat btn-block' onclick='$.updateOrg()'><i class='fa fa-edit'></i> 编辑</button></li>";
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deleteSelectNotice(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            var buttonInsert = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.addNotice()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            // 同上方更新事件同时处理
            //gUpdate == 0 ? strToolBar : strToolBar += buttonUpdate;
            //  strToolBar += buttonDelete;
            strToolBar += "</ul></div> " +
                "<div class='input-group input-group-sm'><input type='text' class='form-control' name='searchText' placeholder='标题'>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: true,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(1).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    var customTemplates = {
        image: function (context) {
            return "<li>" +
                "<a class='btn btn-default' data-wysihtml5-command='insertImage' title='" + context.locale.image.insert +
                "' tabindex='-1' onclick='$.uploadPhoto()'><span class='glyphicon glyphicon-picture'></span></a>" +
                "</li>";
        }
    };
    $('#textId').wysihtml5({
        customTemplates: customTemplates
    });
});
// 搜索框查询操作
$.fn.searchDT = function () {
    var searchText = $("input[name='searchText']").val();
    console.log(searchText);
    gMainDT.search(searchText).draw();
};
//全选框
$.checkChange = function () {
    var isChecked = $("#batch_check").prop('checked');
    $("input[type='checkbox']").prop("checked", isChecked);
};

$.deleteSelectNotice = function (noticeIds) {
    var count = 1;
    if (noticeIds == 0) {
        count = $("input:checkbox[id^='checkbox']:checked").length;
        if (count == 0) {
            $.alert("请选择要删除的数据", 2);
            return;
        } else {
            noticeIds = "";
            $("input:checkbox[id^='checkbox']:checked").each(function () {
                noticeIds += $(this).val() + ",";
            });
            noticeIds = noticeIds.substring(0, noticeIds.length - 1);
        }
    } else {
        noticeIds = noticeIds.noticeId;
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该' + count + '条数据吗?</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: "../rds_noticeadd/deleteSelectNotice",
                    type: "post",
                    dataType: "json",
                    data: {
                        noticeIds: noticeIds
                    },
                    success: function (msg) {
                        gMainDT.ajax.reload(null, false);
                        $.alert("删除成功！", 1);
                        $("#batch_check").attr("checked", false);
                    },
                    error: function (msg) {
                        $.alert("系统错误！", 4);
                    }
                });
            }
        }
    });
};

$.showNotice = function (data) {
    $.ajax({
        url: "../rds_noticeadd/getSelectNoticeSendedOrg",
        type: "post",
        dataType: "json",
        data: {
            noticeId: data.noticeId
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                var data = msg.jsonData;
                var sendedOrgName = data[0].orgName;
                for (var i = 1; i < data.length; i++) {
                    sendedOrgName += "  ,  " + data[i].orgName;
                }
                $("#sendedOrg").text(sendedOrgName);
            }
        },
        error: function () {
            $.alert("系统错误！", 4);
        }
    });
    $("#showNoticeTitle").text(data.noticeTitle);
    $("#showNoticeTime").text(data.noticeSendTime.substring(0, 10));
    $("#showSendName").text(gUserLoginResult.userName);
    $("#showNoticeContent").html(data.noticeContent);
    $("#showInfoModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$.getChoosed = function () {
    var orgCount = 0;
    var orgIds = "";
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = treeObj.getCheckedNodes(true),
        v = "";
    for (var i = 0; i < nodes.length; i++) {
        v += nodes[i].name + ",";
        var str = nodes[i].id;
        var count = 0;
        for (var j = 0; j < str.length; j++) {
            if (str[j] == ",") {
                count++;
            }
        }
        if (count == 1 && nodes[i].pId != 0 && nodes[i].pId != null && nodes[i].pId != "null") {
            orgIds = orgIds + "," + nodes[i].id.split(",")[1];
            orgCount++;
        }
    }
    orgIds = orgIds.substr(1, orgIds.length);
    groupOrgIds = orgIds;
    groupOrgCount = orgCount;
};

$.sendNotice = function () {
    $.getChoosed();
    if (groupOrgCount == 0) {
        $.alert("请选择对象", 2);
    } else if ($("#noticeTitle").val() == 0) {
        $.alert("请填写标题", 3);
    } else if ($("#textId").val() == 0) {
        $.alert("请填写内容", 3);
    } else {
        bootbox.confirm({
            buttons: {
                confirm: {
                    label: '<i class="fa fa-check"></i> 确定',
                    className: 'btn btn-primary btn-flat'
                },
                cancel: {
                    label: '<i class="fa fa-close"></i> 取消',
                    className: 'btn btn-warning btn-flat pull-left'
                }
            },
            message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定将公告发给该' + groupOrgCount + '个公司吗?</b>',
            callback: function (result) {
                if (result) {
                    $.ajax({
                        url: "../rds_noticeadd/addNotice",
                        type: "post",
                        dataType: "json",
                        data: {
                            createUserId: gUserLoginResult.userId,
                            noticeTitle: $("#noticeTitle").val(),
                            noticeContext: $("#textId").val(),
                            orgIds: groupOrgIds
                        },
                        success: function () {
                            $.alert("发送成功！", 1);
                            gMainDT.ajax.reload(null, false);
                            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                            zTree.checkAllNodes(false);
                            zTree.expandAll(false);
                            $.closeNotice();
                        },
                        error: function () {
                            $.alert("系统错误！", 4);
                        }
                    });
                }
            }
        });
    }
};

$.closeNotice = function () {
    $('#textId').parent().find('.wysihtml5-toolbar').remove();
    $('#textId').parent().find('iframe').remove();
    $('#textId').parent().find('input[name*="wysihtml5"]').remove();
    $('#textId').show();
    $('#textId').val("");
    $("#noticeTitle").val("");
    $("#noticeInfoModal").modal("hide");
    $("#textId").wysihtml5();
};

$.getAllOrg = function () {
    $.ajax({
        url: "../rds_noticeadd/getOrgInfo4Notice",
        type: 'post',
        dataType: 'json',
        data: {},
        success: function (msg) {
            var data = msg.jsonData;
            if (msg != null && typeof (msg) != "undefined") {
                var zNodes = new Array();
                var count = 2;
                zNodes[0] = {
                    "id": 1,
                    "pId": 0,
                    "name": "主管公司"
                };
                zNodes[1] = {
                    "id": 2,
                    "pId": 0,
                    "name": "维护公司"
                };
                for (var i = 0; i < data.length; i++) {
                    if (data[i].orgType == 1) {
                        var type = {
                            "id": (1 + "," + data[i].orgId),
                            "pId": 1,
                            "name": data[i].orgName
                        };
                        zNodes[count] = type;
                        count++;
                    }
                    else {
                        var type = {
                            "id": (2 + "," + data[i].orgId),
                            "pId": 2,
                            "name": data[i].orgName
                        };
                        zNodes[count] = type;
                        count++;
                    }
                }

                var setting = {
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    }
                };

                var code;

                function setCheck() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    var type = {"Y": "ps", "N": "ps"};
                    zTree.setting.check.chkboxType = type;
                    showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
                }

                function showCode(str) {
                    if (!code) code = $("#code");
                    code.empty();
                    code.append("<li>" + str + "</li>");
                }

                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                setCheck();
                $("#py").bind("change", setCheck);
                $("#sy").bind("change", setCheck);
                $("#pn").bind("change", setCheck);
                $("#sn").bind("change", setCheck);


                var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                var nodes = treeObj.getNodes();

                var nodeMain = treeObj.getNodeByParam("id", 1);
                var nodeCom = treeObj.getNodeByParam("id", 2);
                if (nodeMain.isParent == true) {
                    treeObj.checkNode(nodeMain, true, true);
                }
                if (nodeCom.isParent == true) {
                    treeObj.checkNode(nodeCom, true, true);
                }


            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
};

$.addNotice = function () {
    $.getAllOrg();
    $("#noticeInfoModalLabel").text("公告发送");
    $("#noticeInfoModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$.uploadPhoto = function () {
    $("#upPhotoModalLabel").text("上传图片");
    $("#upPhotoModal").modal({
        backdrop: 'static',
        keyboard: true,
        show: true
    });
};

$.closeUpPhModal = function () {
    $("#upPhotoModal").modal("hide");
    $("#ossfile").empty();
    clearOssData();
};

$.addImage = function (newUrl) {
    var str = $('#textId').val();
    $('#textId').parent().find('.wysihtml5-toolbar').remove();
    $('#textId').parent().find('iframe').remove();
    $('#textId').parent().find('input[name*="wysihtml5"]').remove();
    $('#textId').show();
    if (str.indexOf("<img>") != 0)
        str = str.substring(0, str.indexOf("<img>") + 4) +
            " width=300px  src = '" + newUrl + "'/" +
            str.substring(str.indexOf("<img>") + 4);
    $('#textId').val(str);
    $("#textId").wysihtml5();
};

$.doneUpPhoto = function () {
    var fileInfo = getOssFileInfo();
    if (fileInfo.length == 0) {
        $.alert("未上传图片", 2);
    } else if (fileInfo.length > 1) {
        $.alert("只需上传一张图片作为证明材料", 3);
    } else {
        $.addImage(fileInfo[0].fileUrl);
        $.closeUpPhModal();
    }
};

//判断文件类型(在需要的js文件添加，文件名务必保持一致)
function judgeFileType(suffix) {
    //图片文件
    if (!(suffix == ".jpg" || suffix == ".JPG" || suffix == ".png" || suffix == ".PNG" ||
        suffix == ".jpeg" || suffix == ".JPEG" || suffix == ".gif" || suffix == ".GIF" ||
        suffix == ".bmp" || suffix == ".BMP")) {
        alert("请选择图片文件！");
        return false;
    }
}

$.closeShowModal = function () {
    $("#showInfoModal").modal("hide");
    $('#body').prop('scrollTop','0');
    fullFlag = true;
    $.fullShowModal();
};

$.fullShowModal = function () {
    if(fullFlag == false) {
        fullFlag = true;
        height = $(document).height() - $("#header").height() - $("#footer").height() - 60;
        width = $(document).width();
        height *= 0.8;
        width *= 0.8;
        $("#dialog").css("top", 0);
        $("#dialog").css("left", -width*0.2);
    } else {
        fullFlag = false;
        height = 400;
        width = 600;
        $("#dialog").css("top", 0);
        $("#dialog").css("left", 0);
    }
    $("#content").css("width", width);
    $("#body").css("width", width + 10);
    $("#body").css("height", height);
    $("#body").css("max-height", height);
};